package model

import (
	"aqchain/pkg/config"
	"aqchain/pkg/log"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	sysLog "log"
	"os"
	"time"
)

// New 初始化函数
func New(cfg config.DatabaseConfig) *gorm.DB {
	log.Logger.Debug("连接数据库")
	var err error
	// gorm配置
	db, err := gorm.Open(mysql.Open(cfg.DSN), &gorm.Config{
		Logger: logger.New(sysLog.New(os.Stdout, "\r\n", sysLog.LstdFlags), logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
		}),
	})
	if err != nil {
		log.Logger.Panic("连接数据库错误", zap.String("error", err.Error()))
	}
	if cfg.AutoMigrate {
		// 自动创建数据库表
		err = db.AutoMigrate(&Block{}, &Account{}, &Item{}, &ItemEvent{}, &Sale{}, &SaleEvent{}, &Auction{}, &AuctionEvent{}, &License{}, &LicenseEvent{}, &LicenseRecord{})
		if err != nil {
			log.Logger.Panic("创建数据库表错误", zap.String("error", err.Error()))
		}
	}

	return db
}
